package com.dcm.seckill.service.impl;

import com.dcm.common.constant.Constants;
import com.dcm.common.exception.MyException;
import com.dcm.seckill.mapper.SeckillMapper;
import com.dcm.seckill.entity.SeckillEntity;
import com.dcm.seckill.service.SeckillService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
/**
 * @author 牛浩
 */
@Service
public class SeckillServiceImpl implements SeckillService {
    @Autowired
    private SeckillMapper seckillMapper;
    @Override
    public List<SeckillEntity> findAll() {
        return seckillMapper.findAll();
    }

    @Override
    public void updateState(Long mid) {
        if (mid == null) {
            throw new MyException(Constants.SecKillErrorMsg.KILL_MID_CANNOT_NULL);
        }
        Integer state = null;
        SeckillEntity miaosha = seckillMapper.findOne(mid);
        if (miaosha.getState()==0){
            state = 1;
        }
        if (miaosha.getState()==1){
            state = 0;
        }
        System.out.println(state);
        seckillMapper.updateState(mid,state);

    }

    @Override
    public SeckillEntity findOne(Long mid) {
        if (mid == null) {
            throw new MyException(Constants.SecKillErrorMsg.KILL_MID_CANNOT_NULL);
        }
        return seckillMapper.findOne(mid);
    }

    @Override
    public void update(SeckillEntity seckill) throws MyException {
        checkMiaosha(seckill);
        seckillMapper.updat(seckill);
    }

    @Override
    public void delete(Long mId) {
        if (mId == null) {
            throw new MyException(Constants.SecKillErrorMsg.KILL_MID_CANNOT_NULL);
        }
        seckillMapper.delete(mId);
    }

    @Override
    public void add(SeckillEntity seckill) throws MyException {
        checkMiaosha(seckill);
        seckill.setCreatDate(new Date());
        seckillMapper.add(seckill);
    }

    @Override
    public List<SeckillEntity> search(Integer state, String name) {
        if (state == null) {
            throw new MyException(Constants.SecKillErrorMsg.KILL_STATE_CANNOT_NULL);
        }
        if (name == null) {
            throw new MyException(Constants.SecKillErrorMsg.KILL_NAME_CANNOT_NULL);
        }
        return seckillMapper.search(state,name);
    }

    /**
     * 抛
     * @param seckill
     * @throws MyException
     */
    private static void checkMiaosha(SeckillEntity seckill) throws MyException {
        if (StringUtils.isBlank(seckill.getImg())){
            throw new MyException(Constants.SecKillErrorMsg.KILL_IMG_CANNOT_NULL);
        }
        if (StringUtils.isBlank(seckill.getName())){
            throw new MyException(Constants.SecKillErrorMsg.KILL_NAME_CANNOT_NULL);
        }
    }
}
